package cn.dinkevin.xui.camera;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.view.SurfaceView;
import android.view.ViewGroup;

import java.io.IOException;

import cn.dinkevin.xui.XUI;
import cn.dinkevin.xui.util.DecimalUtil;
import cn.dinkevin.xui.util.LogUtil;
import cn.dinkevin.xui.util.StringUtil;

/**
 * 视频播放
 * Created by ChengPengFei on 2017/1/4 0004.
 */

public final class PlayerManager {

    private PlayerManager() {
    }

    private static PlayerManager g_singleton = new PlayerManager();

    public static PlayerManager getInstance() {
        return g_singleton;
    }

    private MediaPlayer mediaPlayer;
    private SurfaceView videoDisplayView;
    private MediaPlayer.OnBufferingUpdateListener bufferingUpdateListener = new MediaPlayer.OnBufferingUpdateListener() {
        @Override
        public void onBufferingUpdate(MediaPlayer plMediaPlayer, int i) {

        }
    };

    private MediaPlayer.OnPreparedListener preparedListener = new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
            LogUtil.d("view w:", videoDisplayView.getWidth(), "h:", videoDisplayView.getHeight());

            // 然后开始播放视频
            mp.start();
            isPause = false;

            if (playCallback != null)
                playCallback.onPlayStart();
        }
    };

    private MediaPlayer.OnSeekCompleteListener seekCompleteListener = new MediaPlayer.OnSeekCompleteListener() {
        @Override
        public void onSeekComplete(MediaPlayer mp) {

        }
    };

    private MediaPlayer.OnCompletionListener completionListener = new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            if (playCallback != null)
                playCallback.onPlayOver();
        }
    };

    private MediaPlayer.OnVideoSizeChangedListener videoSizeChangedListener = new MediaPlayer.OnVideoSizeChangedListener() {

        @Override
        public void onVideoSizeChanged(MediaPlayer plMediaPlayer, int width, int height) {

            // 首先取得视频的宽和高
            ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) videoDisplayView.getLayoutParams();
            int vWidth = videoDisplayView.getWidth();
            int vHeight = videoDisplayView.getHeight();

            LogUtil.d("mediaPlayer size:",width,height);
            LogUtil.d("surfaceView size:",vWidth,vHeight);

            int displayW,displayH;
            double vHW = DecimalUtil.divide(vHeight,vWidth);
            double HW = DecimalUtil.divide(height,width);
            if(vHW > HW){
                displayW = vWidth;
                displayH = height * vWidth / width;
            }else{
                displayH = vHeight;
                displayW = width * vHeight / height;
            }

            int wMargin = (vWidth - displayW) / 2;
            int hMargin = (vHeight- displayH) / 2;
            LogUtil.d("video display:",displayW,displayH);
            LogUtil.d("video wMargin:",wMargin,"hMargin:",hMargin);
            //                lp.width = displayW;
//            layoutParams.height = displayH < vHeight ? displayH : vHeight;
            layoutParams.height = displayH;
            layoutParams.width = displayW;
            videoDisplayView.setLayoutParams(layoutParams);
        }
    };

    /**
     * 声明播放器进度回调
     */
    public interface OnPlayCallback {

        /**
         * 当前视频开始播放回调
         */
        void onPlayStart();

        /**
         * 当前视频播放到结尾回调
         */
        void onPlayOver();

        /**
         * 异常回调
         *
         * @param code
         */
        void onPlayError(int code);
    }

    private OnPlayCallback playCallback;

    /**
     * 绑定视频播放进度监听事件
     *
     * @param callback
     */
    public void setOnPlayCallback(OnPlayCallback callback) {
        this.playCallback = callback;
    }

    private String playerDataSource;


    /**
     * 播放指定的视频资源
     *
     * @param videoFilePath 视频路径
     * @param view_display  视频显示 View
     * @param looper        是否循环播放
     * @param resize   是否调整视频播放的尺寸
     */
    public void play(String videoFilePath,SurfaceView view_display,boolean looper,boolean resize){
        stop();

        if (view_display == null) {
            return;
        }
        // 保持屏幕常亮
        videoDisplayView = view_display;
        videoDisplayView.getHolder().setKeepScreenOn(true);
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setDisplay(videoDisplayView.getHolder());
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mediaPlayer.setOnBufferingUpdateListener(bufferingUpdateListener);
        mediaPlayer.setOnPreparedListener(preparedListener);
        mediaPlayer.setOnSeekCompleteListener(seekCompleteListener);
        mediaPlayer.setOnCompletionListener(completionListener);
        mediaPlayer.setLooping(looper);
        if(resize) mediaPlayer.setOnVideoSizeChangedListener(videoSizeChangedListener);
        mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {

            @Override
            public boolean onError(MediaPlayer plMediaPlayer, int what, int extra) {

                LogUtil.e(LogUtil.getTag(PlayerManager.this), "what:", what, "extra:", extra);

                if (what == -38)
                    return true;

                if (null != playCallback) {
                    playCallback.onPlayError(what);
                }
                return true;
            }
        });

        try {
            LogUtil.d(LogUtil.getTag(this), "dataSource:", videoFilePath);
            mediaPlayer.setDataSource(videoFilePath);
            mediaPlayer.prepareAsync();
            playerDataSource = videoFilePath;
        } catch (IOException e) {
            LogUtil.e("setMediaSource", videoFilePath);
            e.printStackTrace();
            if (null != playCallback) {
                playCallback.onPlayError(-1);
            }
        }
    }

    /**
     * 播放指定的视频资源
     *
     * @param videoFilePath 视频路径
     * @param view_display  视频显示 View
     * @param looper        是否循环播放
     */
    public void play(final String videoFilePath, final SurfaceView view_display, boolean looper) {
        play(videoFilePath,view_display,looper,true);
    }

    private AudioManager audioManager;
    private int maxVolume;

    /**
     * 设置音量
     *
     * @param volume 百分比范围从 0 - 100
     */
    public void setVolume(int volume) {
        audioManager = (AudioManager) XUI.getInstance().getContext().getSystemService(Context.AUDIO_SERVICE);
        maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        int curVolume = maxVolume * volume / 100;
        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, curVolume, AudioManager.FLAG_PLAY_SOUND);
    }

    /**
     * 当前是否正在播放
     *
     * @return
     */
    public boolean isPlaying() {
        if (mediaPlayer != null) {
            return mediaPlayer.isPlaying();
        }
        return false;
    }

    private boolean isPause = false;

    /**
     * 暂停播放
     */
    public void pause() {
        if (mediaPlayer != null) {
            mediaPlayer.pause();
            isPause = true;
        }
    }

    /**
     * 当前为暂停状态
     *
     * @return
     */
    public boolean isPause() {
        return isPause;
    }

    /**
     * 继续播放
     */
    public void start() {
        if (isPause && mediaPlayer != null && !StringUtil.isEmpty(playerDataSource)) {
            mediaPlayer.start();
            isPause = false;
        }
    }

    /**
     * 停止播放
     */
    public void stop() {

        playerDataSource = null;
        if (mediaPlayer != null) {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.pause();
                mediaPlayer.seekTo(0);
            }
            mediaPlayer.setDisplay(null);
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }
}
